﻿#region License
// (c) Intergen.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
#endregion

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using TextGlow.Control.Utilities;
using System.Linq;

namespace TextGlow.Control.Controls.Document
{
  public class PagingStackPanel : WrapPanel
  {
    private double _contentWidth;
    private List<UIElement> _remainderChildren = new List<UIElement>();

    public List<UIElement> RemainderChildren
    {
      get { return _remainderChildren; }
    }

    public double ContentWidth
    {
      get { return _contentWidth; }
      set { _contentWidth = value; }
    }

    protected override bool ArrangeLine(double v, double lineV, double availableV, int start, int end, bool useItemU, double itemU, double lineRemainder)
    {
      base.ArrangeLine(v, lineV, availableV, start, end, useItemU, itemU, lineRemainder);

      return false;
    }

    protected override Size MeasureOverride(Size constraint)
    {
      //_remainderChildren.Clear();

      return base.MeasureOverride(constraint);
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
      return base.ArrangeOverride(finalSize);
    }

    protected override bool MeasureLine(int start, int end, double lineRemainder, ref UVSize lineSize)
    {
      base.MeasureLine(start, end, lineRemainder, ref lineSize);

      if (end < Children.Count)
      {
        UIElement wrappingElement = Children[end];
        if (wrappingElement is ISplittable)
        {
          Size availableSpace = new Size(Width, lineRemainder);

          FrameworkElement remainderElement;
          bool hasSplit = ((ISplittable)wrappingElement).Split(availableSpace, out remainderElement);

          if (hasSplit)
          {
            end++;

              remainderElement.Name = Guid.NewGuid().ToString();
              Children.Insert(end, remainderElement);
            ((UserControlExtended)wrappingElement).CustomMeasure(availableSpace);
          }
        }

        _remainderChildren.AddRange(Children.Slice(end, null));

        int count = Children.Count;
        for (int i = end; i < count; i++)
        {
          Children.RemoveAt(Children.Count - 1);
        }
      }

      return true;
    }
  }
}
